package cn.com.dhc.danlu.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import java.util.List;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.MainMenuActivity;
import cn.com.dhc.danlu.activity.goods.GoodInfoActivity;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.fragment.base.BaseV4Fragment;
import cn.com.dhc.danlu.util.CommonConst;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.adapter.GeneralGoodsAdapter;
import cn.com.dhc.danlu.widget.loadlayer.LayerEnum;
import cn.com.dhc.danlu.widget.loadlayer.LoaddingLayout;
import cn.com.dhc.mibd.eufw.widget.android.ptr.CustomListView;
import cn.com.dhc.mibd.eufw.widget.android.ptr.CustomPullToRefreshListView;
import cn.com.dhc.mibd.eufw.widget.android.ptr.PullToRefreshBase;
import cn.com.hd.mall.web.webservices.entity.request.merch.OftenBuyListRequest;
import cn.com.hd.mall.web.webservices.entity.response.merch.OftenBuyListResponse;
import cn.com.hd.mall.web.webservices.entity.response.merch.base.BaseMerchListModel;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;

/**
 * User: Geek_Soledad(wuhaiyang@danlu.com)
 * Date: 2016-08-05
 * Time: 20:55
 * Description:  热卖中 & 已下架
 */
public class AlwaysBuyFragment extends BaseV4Fragment {
    private static final int PAGESIZE = 6;
    private int mPage = 1;

    private boolean isLoad = false;

    //    private IAlwayBuyCallback mAlwayBuyCallback;
    private GeneralGoodsAdapter mGeneralGoodsAdapter;
    private LoaddingLayout mLoaddingLayout;
    private CustomPullToRefreshListView mListView; // 下拉刷新控件

    public static AlwaysBuyFragment newInstance(int status) {
        AlwaysBuyFragment fragment = new AlwaysBuyFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("status", status);
        fragment.setArguments(bundle);
        return fragment;
    }

//    @Override
//    public void onAttach(Context context) {
//        super.onAttach(context);
//        try {
//            mAlwayBuyCallback = (IAlwayBuyCallback) context;
//        } catch (Exception e) {
//            throw new RuntimeException("host activity must imp IAlwayBuyCallback Listener");
//        }
//    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.dl_fragment_alwaysbuy, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mLoaddingLayout = (LoaddingLayout) view;
        mListView = (CustomPullToRefreshListView) view.findViewById(R.id.listview);
        mListView.setMode(PullToRefreshBase.Mode.BOTH);
        mListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<CustomListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<CustomListView> refreshView) {
                //下拉刷新
                fetchData(true);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<CustomListView> refreshView) {
                //上拉刷新回调
                fetchData(false);
            }
        });
        if (getArguments().getInt("status") == 0) {
            mListView.getRefreshableView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    BaseMerchListModel item = (BaseMerchListModel) mGeneralGoodsAdapter.getItem(position - mListView.getRefreshableView().getHeaderViewsCount());
                    Intent intent = new Intent(getContext(), GoodInfoActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString(CommonConst.IntentKey.MERCHANDISE_ID, item.getMerchId());
                    intent.putExtras(bundle);
                    getContext().startActivity(intent);
                }
            });
        }
        mLoaddingLayout.setEmptyViewRetryClickListener(new OnRetryClickListener(LayerEnum.layer_empty));
        mLoaddingLayout.setErrorViewRetryClickListener(new OnRetryClickListener(LayerEnum.layer_error));
        //        mGeneralGoodsAdapter = new GeneralGoodsAdapter(getActivity(), mAlwayBuyCallback.getTaskProxy(), getArguments().getInt("status") == 0 ? GeneralGoodsAdapter.ListType.often_buy_hot : GeneralGoodsAdapter.ListType.often_buy_off);
        mGeneralGoodsAdapter = new GeneralGoodsAdapter(getActivity(),
                getArguments().getInt("status") == 0 ? GeneralGoodsAdapter.ListType.often_buy_hot : GeneralGoodsAdapter.ListType.often_buy_off);
        mListView.getRefreshableView().setAdapter(mGeneralGoodsAdapter);
        fetchData(true);
    }

    /**
     * 获取常购列表数据
     * @param isRefresh
     */
    private void fetchData(final boolean isRefresh) {
        if (isLoad) {
            mListView.onRefreshComplete();
            return;
        }
        if (isRefresh && !mLoaddingLayout.isSuccessView()) {
            mLoaddingLayout.showLoaddingView();
        }
        OftenBuyListRequest request = new OftenBuyListRequest();
        request.setToken(agent.getToken());
        request.setPage(isRefresh ? 1 : mPage);
        request.setRows(PAGESIZE);
        request.setSaleFlag(getArguments().getInt("status") + "");
        isLoad = true;
        agent.getApi()
                .getOftenBuyList(request)
                .compose(OperatorUtils.<OftenBuyListResponse>defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<OftenBuyListResponse>() {
                    @Override
                    protected void onSuccess(OftenBuyListResponse res) {
                        isLoad = false;
                        List<BaseMerchListModel> merchList = res.getOftenBuyListModel();
                        if (isRefresh) {
                            //下拉刷新 (图层 || listview refresh)
                            if (null != merchList && !merchList.isEmpty()) {
                                mPage = 2;
                                if (mLoaddingLayout.isSuccessView()) {
                                    mListView.onRefreshComplete();
                                } else {
                                    mLoaddingLayout.showContentView();
                                }
                            } else {
                                mPage = 1;
                                //successView->empty
                                mListView.onRefreshComplete();
                                mLoaddingLayout.showEmptyView();
                            }
                            mGeneralGoodsAdapter.refreshData(merchList);
                        } else {
                            //上刷新
                            if (null != merchList && !merchList.isEmpty()) {
                                mPage++;
                                mGeneralGoodsAdapter.appendData(merchList);
                            } else {
                                String des = getArguments().getInt("status") == 0 ? "暂无更多热卖商品" : "暂无更多已下架商品";
                                ToastUtil.getInstance().show(des);
                            }
                        }
                        mListView.onRefreshComplete();
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        isLoad = false;
                        ToastUtil.getInstance().show(displayMessage);
                        if (mLoaddingLayout.isSuccessView()) {
                            mListView.onRefreshComplete();
                        } else {
                            mLoaddingLayout.showErrorView(displayMessage);
                        }
                    }
                });
    }

    private class OnRetryClickListener implements View.OnClickListener {
        private LayerEnum mLayerEnum;

        OnRetryClickListener(LayerEnum layerEnum) {
            mLayerEnum = layerEnum;
        }

        @Override
        public void onClick(View v) {
            if (mLayerEnum == LayerEnum.layer_empty) {
                //跳转到采购页面
                Intent intent = new Intent(getActivity(), MainMenuActivity.class);
                intent.putExtra("switchCategory", true);
                startActivity(intent);
                getActivity().finish();
            } else {
                fetchData(true);
            }
        }
    }
}